package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Article;
import com.ywgt.service.ArticleService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/article")
@ApiModel("公告管理")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    /**
     *  page: 1,
     *  limit: 20,
     *  title: undefined,
     *  sort: 'add_time',
     *  order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getArticles(String title,@RequestParam(required = false,defaultValue = "add_time") String sort,
                              @RequestParam(required = false,defaultValue = "desc") String order,
                              @RequestParam(required = false,defaultValue = "1") int page,
                              @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Article> articles=articleService.getArticles(title,page,limit,sort,order);
        List<Article> items = articles.getResult().stream().filter(article -> !article.getDeleted()).collect(Collectors.toList());
        long total = articles.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("total",total);
        data.put("items",items);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Article article){
        if(articleService.removeById(article.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
    @PostMapping("/update")
    public Object update(@RequestBody Article article){
        if(articleService.updateById(article)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @GetMapping("/detail")
    public Object detail(Integer id){
        Article article = articleService.getById(id);
        return ResponseUtil.ok(article);
    }

    @PostMapping("/create")
    public Object create(@RequestBody Article article){
        if(articleService.save(article)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
